import socket
import subprocess
import re
import os
from flask import current_app

def get_all_ips():
    """获取本机所有IP地址"""
    ips = []
    
    # 方法1: 使用socket获取
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        s.close()
        if ip and ip not in ips and not ip.startswith('127.'):
            ips.append(ip)
    except Exception as e:
        current_app.logger.warning(f"使用socket获取IP失败: {e}")
    
    # 方法2: 使用hostname获取
    try:
        hostname = socket.gethostname()
        ip = socket.gethostbyname(hostname)
        if ip and ip not in ips and not ip.startswith('127.'):
            ips.append(ip)
    except Exception as e:
        current_app.logger.warning(f"使用hostname获取IP失败: {e}")
    
    # 方法3: 使用命令行工具获取
    try:
        if os.name == 'nt':  # Windows
            output = subprocess.check_output('ipconfig', shell=True).decode('gbk')
            pattern = r'IPv4.*?(\d+\.\d+\.\d+\.\d+)'
            for match in re.finditer(pattern, output):
                ip = match.group(1)
                if ip and ip not in ips and not ip.startswith('127.'):
                    ips.append(ip)
        else:  # Linux/Mac
            output = subprocess.check_output('ifconfig || ip addr', shell=True).decode('utf-8')
            pattern = r'inet (?:addr:)?(\d+\.\d+\.\d+\.\d+)'
            for match in re.finditer(pattern, output):
                ip = match.group(1)
                if ip and ip not in ips and not ip.startswith('127.'):
                    ips.append(ip)
    except Exception as e:
        current_app.logger.warning(f"使用命令行获取IP失败: {e}")
    
    # 如果没有找到任何IP，添加本地回环地址
    if not ips:
        ips.append('127.0.0.1')
    
    return ips

def get_local_ip():
    """获取本机IP地址"""
    ips = get_all_ips()
    
    # 手动设置公网IP
    public_ip = current_app.config.get('PUBLIC_IP')
    if public_ip and public_ip not in ips:
        ips.insert(0, public_ip)  # 将公网IP添加到列表开头
        return public_ip
    
    # 优先选择192.168开头的IP（通常是局域网IP）
    for ip in ips:
        if ip.startswith('192.168.'):
            return ip
    
    # 其次选择10.开头的IP（通常是VPN或企业网络）
    for ip in ips:
        if ip.startswith('10.'):
            return ip
    
    # 再次选择172.16-172.31开头的IP（也是私有IP范围）
    for ip in ips:
        if re.match(r'^172\.(1[6-9]|2[0-9]|3[0-1])\.', ip):
            return ip
    
    # 如果都没有，返回第一个IP
    return ips[0] if ips else '127.0.0.1' 